package com.huitone.gddw.service.impl.monitoring.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huitone.gddw.dao.entity.InnormalEvent;
import com.huitone.gddw.dao.entity.Trigger;
import com.huitone.gddw.dao.entity.WarnEventTrace;
import com.huitone.gddw.dao.monitoring.warn.IInnormalEventDao;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.dto.monitoring.task.ComHistoryDTO;
import com.huitone.gddw.service.dto.monitoring.task.InnormalTimeTaskDTO;
import com.huitone.gddw.service.dto.monitoring.warn.InnormalEventDTO;
import com.huitone.gddw.service.monitoring.base.IInnormalEventService;
import com.huitone.gddw.service.monitoring.base.ITriggerService;
import com.huitone.gddw.service.monitoring.base.IWarnEventTraceService;
import com.huitone.gddw.utils.StringUtils;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 监控异常事件管理  接口实现类
 * @author wuluodan
 *
 */
@Service
public class InnormalEventService implements IInnormalEventService {

	@Autowired
	private IInnormalEventDao innormalEventDao;
	
	@Autowired
	private IWarnEventTraceService warnEventTraceService;
	
	@Autowired
	private ITriggerService triggerService;
	
	@Override
	public void delByObjId(String objId) {
		innormalEventDao.delByObjId(objId);
	}

	@Override
	public void delByItemId(String itemId) {
		innormalEventDao.delByItemId(itemId);
	}

	@Override
	public void delByKeyId(String keyId) {
		innormalEventDao.delByKeyId(keyId);
	}

	@Override
	public void delByTriggerId(String triggerId) {
		innormalEventDao.delByTriggerId(triggerId);
	}

	@Override
	public QueryPage<Map<String, Object>> selectPage(QueryPage<InnormalEvent> page) {
		Map<String, Object> params = page.getParams();
		params.put("start", (page.getPageNo() - 1) * page.getPageSize() + 1);
		params.put("end", page.getPageNo() * page.getPageSize());
		
		List<InnormalEventDTO> result = innormalEventDao.selectPage(params);
		int totalCount = innormalEventDao.selectCount(params);
		
		List<Map<String, Object>> list = this.collection(result);
		
		QueryPage<Map<String, Object>> queryPage = new QueryPage<Map<String, Object>>();
		queryPage.setResult(list);
		queryPage.setPageNo(page.getPageNo());
		queryPage.setPageSize(page.getPageSize());
		queryPage.setTotalCount(totalCount);
		return queryPage;
	}
	
	/**
	 * 合并数据
	 * @param result List<InnormalEventDTO>
	 * @return List<Map<String, Object>>
	 */
	@SuppressWarnings("unchecked")
	private List<Map<String, Object>> collection(List<InnormalEventDTO> result) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (InnormalEventDTO ie : result) {
			boolean isSame = false;
			for (Map<String, Object> map : list) {
				if (map.get("recId").toString().equals(ie.getRecId())) {
					isSame = true;
					Map<String, Object> m = new HashMap<String, Object>();
					m.put("userName", ie.getUserName());
					m.put("phoneNumber", ie.getPhoneNumber());
					m.put("mailBox", ie.getMailBox());
					
					List<Map<String, Object>> l = (List<Map<String, Object>>)map.get("user");
					l.add(m);
					break;
				}
			}
			if (!isSame) {
				Map<String, Object> map = new HashMap<String, Object>();
				Map<String, Object> mapUser = new HashMap<String, Object>();
				List<Map<String, Object>> listUser = new ArrayList<Map<String, Object>>();
				map.put("recId", ie.getRecId());
				map.put("insertTime", ie.getInsertTime());
				map.put("objId", ie.getObjId());
				map.put("objName", ie.getObjName());
				map.put("warnValue", ie.getWarnValue());
				map.put("highValue", ie.getHighValue());
				map.put("lowerValue", ie.getLowerValue());
				map.put("units", ie.getUnits());
				map.put("warnLevel", ie.getWarnLevel());
				map.put("msg", ie.getMsg());
				map.put("dealStatus", ie.getDealStatus());

				mapUser.put("userName", ie.getUserName());
				mapUser.put("phoneNumber", ie.getPhoneNumber());
				mapUser.put("mailBox", ie.getMailBox());
				listUser.add(mapUser);
				map.put("user", listUser);
				
				list.add(map);
			}
		}
		return list;
	}

	@Override
	public InnormalEvent getById(String recId) {
		return innormalEventDao.getById(recId);
	}

	@Override
	public void update(InnormalEvent entity, WarnEventTrace warnEventTrace) {
		entity.setLastModTime(new Date());
		entity.setLastModStaffId(SysLoginUtil.getLoginUserId());
		innormalEventDao.update(entity);
		
		warnEventTrace.setTriggerid(entity.getTriggerId());
		warnEventTrace.setEventId(entity.getRecId());
		warnEventTraceService.save(warnEventTrace);
	}

	@Override
	public void autoCreateInnormalEvent() {
		/*Date curDate = new Date();
		List<InnormalTimeTaskDTO> result = innormalEventDao.findInnormal(curDate);
		if (null == result || 0 == result.size()) {
			return;
		}
		
		collectInnormal(result);
		for (InnormalTimeTaskDTO innormalTimeTaskDTO : result) {
			InnormalEvent lastInnormalEvent = innormalTimeTaskDTO.getInnormalEvent();
			int i = 0;
			for (InnormalEvent innormalEvent : innormalTimeTaskDTO.getCollection()) {
				// 第一条为异常数据时
				if (0 == i && 1 == innormalEvent.getIsFirstInnormal()) {
					// 存在未自动处理的异常信息时
					if (lastInnormalEvent != null && StringUtils.isNotBlank(lastInnormalEvent.getRecId())) {
						// 更新异常持续时长和异常次数
						lastInnormalEvent.setLongTime(lastInnormalEvent.getLongTime() + innormalEvent.getLongTime());
						lastInnormalEvent.setTimes(lastInnormalEvent.getTimes() + innormalEvent.getTimes());
						lastInnormalEvent.setValue(innormalEvent.getValue());
						lastInnormalEvent.setMsg(innormalEvent.getMsg());
						// 恢复正常
						if (0 == innormalEvent.getIsLastInnormal()) {
							lastInnormalEvent.setAutoDealStatus("1");
						}
						innormalEventDao.update(lastInnormalEvent);
					} else {
						// 恢复正常
						if (0 == innormalEvent.getIsLastInnormal()) {
							innormalEvent.setAutoDealStatus("1");
						}
						innormalEventDao.save(innormalEvent);
					}
				} else {
					
				}
				
				i++;
			}
			// 第一条为异常数据时
//			if (1 == innormalTimeTaskDTO.getIsFirstInnormal()) {
//				// 存在未自动处理的异常信息时
//				if (innormalEvent != null && StringUtils.isNotBlank(innormalEvent.getRecId())) {
//					
//					// 更新异常持续时长和异常次数
//					innormalEvent.setLongTime(innormalEvent.getLongTime() + innormalTimeTaskDTO.getUpdatetime());
//					innormalEvent.setTimes(innormalEvent.getTimes() + 1);
//					innormalEventDao.update(innormalEvent);
//				} else {
//					
//				}
//			} else { 
//				if (innormalEvent != null) {
//					
//				} else {
//					
//				}
//			}
		}
		
		triggerService.updateLastTimerTime(result, curDate);*/
	}
	
	/**
	 * 合并异常数据
	 * @param result
	 */
	private void collectInnormal(List<InnormalTimeTaskDTO> result) {
		int j = 0;
		for (InnormalTimeTaskDTO innormalTimeTaskDTO : result) {
			List<InnormalEvent> collection = innormalTimeTaskDTO.getCollection();
			List<ComHistoryDTO> list = new ArrayList<>();
			ComHistoryDTO lastHistoryDTO = new ComHistoryDTO();
			int i = 0;
			for (ComHistoryDTO comHistoryDTO : innormalTimeTaskDTO.getHistorys()) {
				if (0 == i) {
					list.add(i, comHistoryDTO);
				} else {
					if (comHistoryDTO.getRownumber() == lastHistoryDTO.getRownumber() + 1) {
						list.add(i, comHistoryDTO);
					} else {
						InnormalEvent innormalEvent = new InnormalEvent();
						innormalEvent.setTriggerId(innormalTimeTaskDTO.getTriggerId());
						innormalEvent.setTimes(list.size());
						innormalEvent.setLongTime((list.size() - 1) * innormalTimeTaskDTO.getUpdatetime());
						
						ComHistoryDTO firstHistory = list.get(0);
						ComHistoryDTO lastHistory = list.get(list.size() - 1);
						innormalEvent.setValue(lastHistory.getValue());
						innormalEvent.setMsg(innormalTimeTaskDTO.getInnormalMsg());
//						innormalEvent.setIsFirstInnormal(firstHistory.getIsFirstInnormal());
//						innormalEvent.setIsLastInnormal(lastHistory.getIsLastInnormal());
						
						collection.add(j, innormalEvent);
						j++;
						list = new ArrayList<>();
						i = 0;
						list.add(i, comHistoryDTO);
					}
				}
				lastHistoryDTO = comHistoryDTO;
				i++;
			}
		}
	}

	@Override
	public List<InnormalEventDTO> findWarn() {
		return innormalEventDao.findWarn();
	}

}
